package com.sky.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyuncs.exceptions.ClientException;
import com.sky.properties.AliOssProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Component
@Slf4j
public class AliyunOOSUtil {

    @Autowired
    private AliOssProperties aliOssProperties;


    public String upload(byte[] fileContent, String OriginalFileName) throws ClientException {

        String endpoint = aliOssProperties.getEndpoint();
        String bucketName = aliOssProperties.getBucketName();
//        String accessKeyId = aliOssProperties.getAccessKeyId();
//        String accessKeySecret = aliOssProperties.getAccessKeySecret();

        // 获得本地环境变量里的 OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET
        EnvironmentVariableCredentialsProvider environmentVariableCredentialsProvider
                = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        log.info("上传信息endpoint id和key {}\n{}", endpoint, environmentVariableCredentialsProvider);
        String dir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM"));
        String fileName = UUID.randomUUID() + OriginalFileName.substring(OriginalFileName.lastIndexOf("."));

        String objectName = dir + "/" + fileName;

        try {
            //创建客户端
            OSS oosClient = new OSSClientBuilder()
                    .build(endpoint, environmentVariableCredentialsProvider);

            //添加对象到OOS
            oosClient.putObject(bucketName, objectName, new ByteArrayInputStream(fileContent));
        } catch (OSSException | com.aliyun.oss.ClientException e) {
            throw new RuntimeException(e);
        }

        //返回文件名
        return endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + objectName;

    }


}
